package com.sc.demo1.common.algorithm;


import com.sc.common.exception.BusinessException;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.PropertiesUtil;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.util.Collection;
import java.util.Properties;

/**
 * 按公司ID分库
 * 确分片算法类名称，用于=和IN
 */
public class DatabaseShardingByCompanyIdAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        // 分片列
        String shardingColumnName = preciseShardingValue.getColumnName();

        // 分片列的值
        Long shardingColumnValue = preciseShardingValue.getValue();

        if(shardingColumnValue == null ){
            throw new BusinessException("定位表失败：分片列["+shardingColumnName+"]对应的值为空！");
        }

        Properties properties = PropertiesUtil.getDataSourceCompanyMapProperties();

        String dsNameStr = properties.getProperty(shardingColumnValue+"");
        if(MyStringUtils.isNotBlank(MyStringUtils.null2String(dsNameStr))){
            String[] dsNames = dsNameStr.split(",");
            return dsNames[0];
        }
        return null;
    }
}
